jQuery.fn.fileselector = function() {
    var fileTreeItemSelector = 'li.file a';
    var fileSelectorClass = 'file_selector';
    var activeClass = 'accept_file';
    var highlightClass = 'ui-state-highlight';
    var activate = function(id) {
        $('#' + id).addClass(activeClass);
        $('#' + id).addClass(highlightClass);
    }
    var clear = function() {
        $('.' + fileSelectorClass).removeClass(activeClass);
        $('.' + fileSelectorClass).removeClass(highlightClass);
        $('.file_selector_link span').remove();
        $.dig.ui.message.hide();
    }
    $('form input, form select, form textarea').click( function() { 
        if(! $(this).hasClass(activeClass)) {
            clear();
        }
    });
    var current = function() {
        return $('.' + fileSelectorClass + '.' + activeClass);
    }
    var isImage = function(extension) {
        var imageExtensions = 'png,gif,jpg,jpeg';
        if(imageExtensions.indexOf($extension) >= 0) {
            return true;
        } else {
            return false;
        }
    }
    $('a.select_file').live('click', (function(){
        clear();
        $(this).after('<span style="margin-left:10x">...now double click a file from the site tree to insert it.</span>');
        activate($(this).attr('rel'));
    }));
    $(fileTreeItemSelector).dblclick(function() {
        $.post('digCms/item/json-details', {id: $(this).attr('rel')}, function(response) {
            var input = current();
            console.log(input);
            var extension = response.filepath.split('.').pop();
            console.log(input);
            if(input.attr('accept').indexOf(extension) >= 0) {
                input.val(response.filepath);
                clear();
            } else {
                $.dig.ui.message.add('This control only allows files of the following types: ' + allowedExtensions);
            }
        }, 'json');
    });
    return this.each(function(){
        $(this).addClass('file_selector');
        $(this).after('<p class="file_selector_link"><a href="#" class="select_file" rel="' + $(this).attr('id') + '>Select a file</a></p>');
    });
}
